package jm.mq;

import com.rabbitmq.client.*;

/**
 * @Description 消费者代码
 * @date 2022/3/4 19:31
 */
public class Consumer {

    // 队列名称
    private static final String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        // 配置连接IP
        factory.setHost("8.140.23.138");

        // 配置RabbitMQ用户名和密码
        factory.setUsername("guest");
        factory.setPassword("guest");

        // 建立连接
        Connection connection = factory.newConnection();

        // 创建信道
        Channel channel = connection.createChannel();

        // 声明：接收消息回调
        DeliverCallback deliverCallback = (consumerTag,message) -> {
            System.out.println(new String(message.getBody()));
        };

        // 声明：取消消费回调
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("消费者取消消费");
        };

        // 消费消息
        /**
         * basicConsume
         *            1. 消费的队列名称
         *            2. 成功之后是否自动应答
         *            3. 接收到消息的回调
         *            4. 消费者取消消费的回调
         */
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
    }

}
